<?php
require_once(dirname(__FILE__)."/../push/PushNotification.php"); 

class WinController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column3';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','user','check'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('rolls','select','push','winning'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * 首页
	 * @param  [type] $eventid [description]
	 * @return [type]          [description]
	 */
	public function actionIndex(){
		$events = Event::model()->findAll();
		$this->render('index',array(
			'events'=>$events
		));
	}


	/**
	 * 轮动抽奖中奖
	 * @param  [type] $eventid [description]
	 * @return [type]          [description]
	 */
	public function actionWinning($ticket){
		$ts = explode(' ' , $ticket);
		// var_dump($ts);
		if (count($ts) > 2) {
			$ticket_db = Ticket::model()->find("userid=:u and eventid=:e and code=:c", 
			array(
				':u'=>intval($ts[0]) ,
				':e'=>intval($ts[1]) ,
				':c'=>intval($ts[2]) 
				));

			$user_db = User::model()->findByPk(intval($ts[0]));
			$event_db = Event::model()->findByPk(intval($ts[1]));

			// echo intval($ts[0]);
			// var_dump($ticket_db);
			// var_dump($user_db);
			if ($ticket_db !== null && $user_db !== null && $event_db !== null) {

				$ticket_db->winning = 1;
				$ticket_db->wintime = date("Y-m-d H:i:s" ,time());

				$ticket_db->save();

				$ret = array(
					'id'=>$ticket_db->id,
					'event'=>$event_db->title,
					'username'=>$user_db->username,
					'mobile'=>$user_db->mobile ,
					'stat'=>$ticket_db->stat,
					'winning'=>$ticket_db->winning,
					'wintime'=>$ticket_db->wintime,
					'time'=>$ticket_db->createtime
					);
				$this->bingoToTicket($ticket_db);
				ob_end_clean();
            	function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start();
				echo json_encode(array('code'=> 0 , 'data'=>$ret));
			}else{
				echo json_encode(array('code'=> 1001 , 'message'=>'没有找到对应的用户和奖券。'));
			}
		}else{
			echo json_encode(array('code'=> 1000 , 'message'=>'请注意！奖号之间有两个空格。'));
		}
	}


	private function bingoToTicket($ticket){

		// bingoToUser($level, $eventid, $userid){

		// $push_data = array();
		 
		// $push_data[] = array("id" => $ticket->id,
		// 	"eventid" => $ticket->eventid,
		// 	"userid" => $ticket->userid,
		// 	"code" => $ticket->code,
		// 	"winning" => ''.$ticket->winning,
		// 	"createtime" => $ticket->createtime
		// 	);
		 
		// $level = $ticket->winning;
		// $award = Globals::award();
		
		// $title = '恭喜您'.$names.'！您中奖了！';
		// $message = '您刚刚中了'.$this->award($eventid , intval($ticket['winning'])).'，请到领奖处兑奖。';
		
		// $message = '恭喜！有1位摇吧用户，刚刚中了'.$award[intval($level)].'奖，请到领奖处兑奖。';
		// echo $message;
		// // return;
		// // // 发送Android 通知
		// echo "=== Andorid Push ===<br>";
		// android_push_message($message, array('data'=>$push_data));
		// // android_push_message($message, array('data'=>$push_data));
		// // 发送IOS 通知
		// // 只给中奖的人推送通知
		// // 给所有人推送消息
		// // var_dump(json_encode($push_data).'<br>');
		// echo "=== IOS Push ===<br>";
		// $iospushs = Iospush::model()->findAll('os=:os', array(':os'=>'ios'));

		// foreach ($iospushs as $model) {
		// 	// 判断是否是中奖者，如果是
		// 	$myself = false;
		// 	$names='';
			
		// 	if($model->userid === $ticket->userid){
		// 		$myself=true;
		// 		$user=User::model()->findByPk($ticket->userid);
		// 		if($user!==null){
		// 			$names = $user->username;
		// 		}
		// 		break;
		// 	}
			
		// 	// 中奖者和其他人的信息不同
		// 	// echo $myself." = ".$names.'<Br>';
		// 	try{


		// 	if ($myself) {
		// 		echo '|'.$model->token.'||'.Yii::app()->params['pushserver'];
			
		// 		$ret = ios_push_message(
		// 			$model->token,
		// 			1,
		// 			$ticket->id.','.$ticket->userid.','.
		// 			$ticket->eventid.','.$ticket->code.','.
		// 			$ticket->winning,
		// 			Yii::app()->params['pushserver'],

		// 			'恭喜！'.$names.'，您刚刚中了'.$award[intval($ticket->winning)].'奖，请到领奖处兑奖。');

		// 		echo '<br>';
			
		// 	}else{	
		// 		// echo $model->token.'||'.Yii::app()->params['pushserver'];
			
		// 		// $ret = ios_push_message(
		// 		// $model->token,
		// 		// 1,
		// 		// '', 
		// 		// Yii::app()->params['pushserver'],
		// 		// $message);
		// 		// echo '<br>';
		// 	}
		// 	}catch(Exception $e){
		// 		echo "Error".$e;
		// 	}

		// }

	}
	
	/**
	 * 轮动随机中奖方法.
	 */
	public function actionRolls($eventid)
	{
		$limit = 50;
		$count = Ticket::model()->count('winning=0 and eventid='.$eventid);
		// echo('winning=0 and eventid='.$eventid.' limit '.$postion.','.$limit);
		$roll = array();
		for ($i=0; $i < $limit ; $i++) { 
			$postion = rand(0,$count);
			$ret = Ticket::model()->findAll('winning=0 and eventid='.$eventid.' limit '.$postion.',1');
			if (count($ret) > 0) {
				$roll[] = $ret[0];
			}
		}

		$this->render('admin',array(
			'ret'=>$roll
		));
		// Yii::app()->end();
	}
	/**
	 * 选择随机中奖界面
	 * @return [type] [description]
	 */
	public function actionSelect(){
		$model = new SelectForm;

		if(isset($_POST['SelectForm']))
		{
			// header('Content-type: application/json;charset=utf-8');
			$model->attributes=$_POST['SelectForm'];
			header('Content-type: text/html;charset=utf-8');
			// var_dump($model);
			if(empty($model->userid)){
				// 真是中奖信息
				$this->bingo($model->level, $model->num , $model->eventid);
				// echo "bingo";
			}else{

				// 测试中奖信息
				$this->bingoToUser($model->level, $model->eventid , $model->userid);
			}
			return;
			// if($model->save())
				// $this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	private function bingoToUser($level, $eventid, $userid){
		$ticket = null;

		$model = Ticket::model()->find('winning=0 and eventid='.$eventid.' and userid='.$userid.'' );
		if($model !== null){
			$model->winning = intval($level);
			$model->wintime = date("Y-m-d H:i:s" ,time());
			if($model->save()){
				$ticket = $model;
			}
		}


		// 抽奖完毕，发送中奖消息。
		echo '已抽出1人中'.$level.'等奖，准备发送通知。'.'<br><br>';

	 
		$push_data = array();
		 
		$push_data[] = array("id" => $ticket['id'],
			"eventid" => $ticket['eventid'],
			"userid" => $ticket['userid'],
			"code" => $ticket['code'],
			"winning" => ''.$this->award($eventid , intval($ticket['winning'])),
			"createtime" => $ticket['createtime']
			);
		 
		   
		$names='';
			 
		$user=User::model()->findByPk($userid);
		if($user!==null){
			$names = $user->username;
		}

		$title = $names.',您中奖了!';
		$message = '您刚刚中了'.$this->award($eventid , intval($ticket['winning'])).',点击查看详情。';
		echo $title.$message.'<br><br>';



		$iospushs = Iospush::model()->find(' userid=:u', 
			array(':u'=>$userid));

		if ($iospushs !== null) {
			if ($iospushs->os === 'ios') {
				// 发送IOS 通知
				// 只给中奖的人推送通知
				// 给所有人推送消息
				echo "=== IOS Push ===".$iospushs->token."<br>";
				// 中奖者和其他人的信息不同
				// echo $myself." = ".$names.'<Br>';
				try{
				 
					echo Yii::app()->params['pushserver'];
				
					$ret = ios_push_message(
						$iospushs->token,
						1,
						$ticket['id'].','.$ticket['userid'].','.
						$ticket['eventid'].','.$ticket['code'].','.
						$ticket['winning'],
						Yii::app()->params['pushserver'],
						'恭喜您！'.$message);

					echo '<br>';
				
				 
				}catch(Exception $e){}


			}else{
				try{

				// 发送Android 通知
					echo "=== Andorid Push ===".$iospushs->token."<br>";
					android_push_message($iospushs->token, $title , $message, array('data'=>$push_data));
				}catch(Exception $e){}
			}
		}
	}

	/**
	* 
	*/
	private function sendMessage(){

	}

	private function award($eventid, $level){
		// echo $eventid ."||". $level;
		$model = Event::model()->findByPk($eventid);

		if ($model !== null) {
			$idx = 0;
			// echo $model->award;
			$award = explode("\r\n", $model->award);
			// var_dump($award);

			foreach ($award as $v) {
				// echo $level ."|". $idx;
				if ($level == ($idx+1) {
					// echo $v;
					return $v;
				}
				$idx++;
			}
		}
	}
	/**
	 * 手工抽奖接口
	 * @param  [type] $level   [description]
	 * @param  [type] $num     [description]
	 * @param  [type] $eventid [description]
	 * @param  [type] $code    [验证吗]
	 * @return [type]          [description]
	 */
	private function bingo($level, $num, $eventid){
		// header('Content-type: application/json;charset=utf-8');
		 

		// $key = $level.''.$num.''.$eventid;
		// $md5code = md5($key.strlen($key));
		// echo $md5code.'|'.$code;

		// if(0 !== strcmp($code , $md5code) ){
		// 	echo '{"code": 1006}';
		// 	return;
		// }
		// 获得奖池中所有未中奖的奖券
		// $count = Ticket::model()->count('winning=0 and eventid='.$eventid);

		// $criteria =new CDbCriteria; 

		$users = Yii::app()->db->createCommand()
		->selectDistinct('userid')
		->from('ticket')
		->where('winning=0 and eventid=:id', array(':id'=>$eventid))
		->queryAll();

		$count = count($users) - 1;

		echo "奖池共有奖券 = ".$count.'<br><br>';
		$bingo = array();
		for ($i=0; $i < $num; $i++) { 
			// 随机定位一个中奖名额，并找出它
			$postion = rand(0,$count-$i);

			$user = $users[$postion];

			// var_dump($user['userid']);
			// $model = Ticket::model()->findAll('winning=0 and eventid='.$eventid.' limit '.$postion.',1' );
			// echo 'winning=0 and eventid='.$eventid.' limit '.$postion.',1<br>';

			$user_ticket = Ticket::model()->count('winning<>0 and eventid='.$eventid.' and userid='.$user['userid'] );
			if($user_ticket < 3){
				$this->bingoToUser($level, $eventid, $user['userid']);
			}else{
				$i--;
			}
			 
		}
		
		// // 抽奖完毕，发送中奖消息。
		// echo '已抽出'.count($bingo).'人中'.$level.'等奖，准备发送通知。'.'<br><br>';
		// $names = '';
		// $push_data = array();
		// foreach ($bingo as $ticket) {
		// 	$push_data[] = array("id" => $ticket['id'],
		// 		"eventid" => $ticket['eventid'],
		// 		"userid" => $ticket['userid'],
		// 		"code" => $ticket['code'],
		// 		"winning" => ''.$ticket['winning'],
		// 		"createtime" => $ticket['createtime']
		// 		);
		// }
		// // if (strlen($names)>1) {
		// // 	$names = substr($names,0,strlen($names)-1);
		// // }
		// $award = Globals::award();

		// if(1 === intval($level)){
		// 	$levelname = "一";
		// }else if(2 === intval($level)){
		// 	$levelname = "二";
		// }else if(3 === intval($level)){
		// 	$levelname = "三";
		// }else if(4 === intval($level)){
		// 	$levelname = "特";
		// }
		// $message = '恭喜！有'.count($bingo).'位摇吧用户，刚刚中了'.$award[intval($level)].'奖，请到领奖处兑奖。';
		// echo $message.'<br><br>';


		// // // 发送Android 通知
		// echo "=== Andorid Push ===<br>";
		// android_push_message($message, array('data'=>$push_data));
		// // android_push_message($message, array('data'=>$push_data));
		// // 发送IOS 通知
		// // 只给中奖的人推送通知
		// // 给所有人推送消息
		// // var_dump(json_encode($push_data).'<br>');
		// echo "=== IOS Push ===<br>";
		// $iospushs = Iospush::model()->findAll('os=:os', array(':os'=>'ios'));

		// foreach ($iospushs as $model) {
		// 	// 判断是否是中奖者，如果是
		// 	$myself = false;
		// 	$names='';
		// 	foreach ($bingo as $ticket) {
		// 		if($model->userid === $ticket->userid){
		// 			$myself=true;
		// 			$user=User::model()->findByPk($ticket->userid);
		// 			if($user!==null){
		// 				$names = $user->username;
		// 			}
		// 			break;
		// 		}
		// 	}
		// 	// 中奖者和其他人的信息不同
		// 	// echo $myself." = ".$names.'<Br>';
		// 	try{


		// 	if ($myself) {
		// 		echo '|'.$model->token.'||'.Yii::app()->params['pushserver'];
			
		// 		$ret = ios_push_message(
		// 			$model->token,
		// 			1,
		// 			$ticket['id'].','.$ticket['userid'].','.
		// 			$ticket['eventid'].','.$ticket['code'].','.
		// 			$ticket['winning'],
		// 			Yii::app()->params['pushserver'],

		// 			'恭喜！'.$names.'，您刚刚中了'.$award[intval($ticket['winning'])].'奖，请到领奖处兑奖。');

		// 		echo '<br>';
			
		// 	}else{	
		// 		// echo $model->token.'||'.Yii::app()->params['pushserver'];
			
		// 		// $ret = ios_push_message(
		// 		// $model->token,
		// 		// 1,
		// 		// '', 
		// 		// Yii::app()->params['pushserver'],
		// 		// $message);
		// 		// echo '<br>';
		// 	}
		// 	}catch(Exception $e){}

		// }
		// $ret = ios_push_message(
		// 	'f3125b3a7e2389d573e27ddcc6a54bee6992a680af0f4f2b25a5bc11ce8bffb9',
		// 	1,
		// 	$push_data,
		// 	Yii::app()->params['pushserver'],
		// 	$message);
		// echo '推送成功='.$ret;
	}



	/**
	 * 兑奖界面
	 * @return [type] [description]
	 */
	public function actionCheck($ticket = '', $tid = 0){
		if ($ticket === '' && $tid === 0) {
			$this->render('check',array(
				'ret'=>array(),
			));
		}else{
			header('Content-type: application/json;charset=utf-8');

			if ($tid !== 0) {
				$ticket_db = Ticket::model()->findByPk(intval($tid));
				if ($ticket_db === null) {
					echo json_encode(array('code'=> 1001 , 'message'=>'没有找到对应的用户和奖券。'));
				}else{
					$ticket_db->stat = 1;
					$ret = $ticket_db->save();
					if ($ret) {
						echo json_encode(array('code'=> 0 , 'message'=>'<span style="color:green">兑奖成功请发送礼物。</span>'));
					}else{
						echo json_encode(array('code'=> 1002 , 'message'=>'保存失败，再试一次。'));
					}
				}
				return;
			}
			$ts = explode(' ' , $ticket);
			// var_dump($ts);
			if (count($ts) > 2) {
				$ticket_db = Ticket::model()->find("userid=:u and eventid=:e and code=:c", 
				array(
					':u'=>intval($ts[0]) ,
					':e'=>intval($ts[1]) ,
					':c'=>intval($ts[2]) 
					));

				$user_db = User::model()->findByPk(intval($ts[0]));
				$event_db = Event::model()->findByPk(intval($ts[1]));

				// echo intval($ts[0]);
				// var_dump($ticket_db);
				// var_dump($user_db);
				if ($ticket_db !== null && $user_db !== null && $event_db !== null) {
					$ret = array(
						'id'=>$ticket_db->id,
						'event'=>$event_db->title,
						'username'=>$user_db->username,
						'mobile'=>$user_db->mobile,
						'stat'=>$ticket_db->stat,
						'winning'=>$ticket_db->winning,
						'wintime'=>$ticket_db->wintime,
						'time'=>$ticket_db->createtime
						);
					echo json_encode(array('code'=> 0 , 'data'=>$ret));
				}else{
					echo json_encode(array('code'=> 1001 , 'message'=>'没有找到对应的用户和奖券。'));
				}
			}else{
				echo json_encode(array('code'=> 1000 , 'message'=>'请注意！奖号之间有两个空格。'));
			}
		}
	}

	/**
	 * 测试推送信息
	 * @return [type] [description]
	 */
	public function actionPush(){
		$push_data = array();
		
		// $push_data[] = array("id" => 11,
		// 		"eventid" => 11,
		// 		"code" =>11,
		// 		"winning" => time());

		// $push_data[] = array("id" => 22,
		// 		"eventid" => 22,
		// 		"code" => 22,
		// 		"winning" => time());

		// $push_data[] = array("id" => 22,
		// 		"eventid" => 22,
		// 		"code" => 22,
		// 		"winning" => time());

		// $push_data[] = array("id" => 22,
		// 		"eventid" => 22,
		// 		"code" => 22,
		// 		"winning" => time());

		// var_dump($push_data);
		
		// $ret = ios_push_message(
		// 	'f3125b3a7e2389d573e27ddcc6a54bee6992a680af0f4f2b25a5bc11ce8bffb9',
		// 	1,
		// 	"9,1,1,234,3",
		// 	Yii::app()->params['pushserver'],'恭喜！张舰，您刚刚中了三等奖，请到领奖处兑奖。');
		// echo '推送成功='.$ret;
		// // 发送Android 通知
		echo "=== Andorid Push ===<br>";
		// $message = "亲爱的用户，感谢您在摇吧内测期间安装和使用摇吧应用，为了您能顺利的参与到摇奖的游戏中来，如果您装的是内测版程序，请您卸载摇吧应用，重新下载安装正式版应用。";
		// android_push_message($message, array('data'=>$push_data));
	}

}
